package com.ruoyi.base.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.base.domain.BaseCatalog;
import com.ruoyi.base.domain.BaseSubject;
import com.ruoyi.base.mapper.BaseSubjectMapper;
import com.ruoyi.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Validator;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.base.mapper.BaseDocumentMapper;
import com.ruoyi.base.domain.BaseDocument;
import com.ruoyi.base.service.IBaseDocumentService;

/**
 * 文档信息Service业务层处理
 * 
 * @author yepanpan
 * @date 2025-02-12
 */
@Service
public class BaseDocumentServiceImpl implements IBaseDocumentService 
{
    private static final Logger log = LoggerFactory.getLogger(BaseDocumentServiceImpl.class);

    @Autowired
    private BaseDocumentMapper baseDocumentMapper;
    @Autowired
    private BaseSubjectMapper baseSubjectMapper;

    @Autowired
    protected Validator validator;
    /**
     * 查询文档信息
     * 
     * @param id 文档信息主键
     * @return 文档信息
     */
    @Override
    public BaseDocument selectBaseDocumentById(Long id)
    {
        return baseDocumentMapper.selectBaseDocumentById(id);
    }

    /**
     * 查询文档信息列表
     * 
     * @param baseDocument 文档信息
     * @return 文档信息
     */
    @Override
    public List<BaseDocument> selectBaseDocumentList(BaseDocument baseDocument)
    {
        return baseDocumentMapper.selectBaseDocumentList(baseDocument);
    }

    /**
     * 新增文档信息
     * 
     * @param baseDocument 文档信息
     * @return 结果
     */
    @Override
    public int insertBaseDocument(BaseDocument baseDocument)
    {
        baseDocument.setCreateTime(DateUtils.getNowDate());
        return baseDocumentMapper.insertBaseDocument(baseDocument);
    }

    /**
     * 修改文档信息
     * 
     * @param baseDocument 文档信息
     * @return 结果
     */
    @Override
    public int updateBaseDocument(BaseDocument baseDocument)
    {
        baseDocument.setUpdateTime(DateUtils.getNowDate());
        return baseDocumentMapper.updateBaseDocument(baseDocument);
    }

    /**
     * 批量删除文档信息
     * 
     * @param ids 需要删除的文档信息主键
     * @return 结果
     */
    @Override
    public int deleteBaseDocumentByIds(Long[] ids)
    {
        return baseDocumentMapper.deleteBaseDocumentByIds(ids);
    }

    /**
     * 删除文档信息信息
     * 
     * @param id 文档信息主键
     * @return 结果
     */
    @Override
    public int deleteBaseDocumentById(Long id)
    {
        return baseDocumentMapper.deleteBaseDocumentById(id);
    }


    /**
   * 导入数据
   *
   * @param dataList 数据列表
   * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
   * @param operName 操作用户
   * @return 结果
   */
    @Override
    public String importData(List<BaseDocument> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Map<String, Long> subjectMap = baseSubjectMapper.selectBaseSubjectList(new BaseSubject()).stream().collect(Collectors.toMap(BaseSubject::getName, BaseSubject::getId));
        for (BaseDocument row : dataList)
        {
            try
            {
                row.setSubjectId(subjectMap.get(row.getSubjectName()));
                BeanValidators.validateWithException(validator, row);


                // 验证是否存在旧数据
                BaseDocument old = baseDocumentMapper.selectBaseDocumentByNum(row.getNum());
                if (StringUtils.isNull(old))
                {
                    row.setCreateBy(operName);
                    insertBaseDocument(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、文档 " + row.getNum() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    row.setId(old.getId());
                    row.setUpdateBy(operName);
                    updateBaseDocument(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、文档 " + row.getNum() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、文档 " + row.getNum() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、文档 " + row.getNum() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
